//
//  ANTabBar.m
//  Ants
//
//  Created by ZHM on 16/3/11.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANTabBar.h"
#import "ANTabBarButton.h"

@interface ANTabBar ()

@property (nonatomic, strong) NSMutableArray *buttons;

@property (nonatomic, weak) UIButton *selectedButton;
@end


@implementation ANTabBar

- (NSMutableArray *)buttons
{
    if (_buttons == nil) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}


//调整子控件的位置
- (void)layoutSubviews {
    [super layoutSubviews];
    self.backgroundColor = [UIColor clearColor];// colorWithAlphaComponent:0.4];
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    CGFloat btnW = self.bounds.size.width / self.items.count;
    CGFloat btnH = self.bounds.size.height;
    int i = 0;
    //调整系统自带的TabBar上得子控件位置
    for (UIView *tabBarButton in self.subviews) {
        btnX = i * btnW;
        tabBarButton.frame = CGRectMake(btnX, btnY, btnW, btnH);
        i++;
    }
}

// 点击tabBarButton调用
-(void)btnClick:(UIButton *)button
{
    _selectedButton.selected = NO;
    button.selected = YES;
    _selectedButton = button;
    // 通知tabBarVc切换控制器，
    if ([_delegate respondsToSelector:@selector(tabBar:didClickButton:)]) {
        [_delegate tabBar:self didClickButton:button.tag];
    }
}

- (void)setItems:(NSArray *)items
{
    _items = items;
    // 遍历模型数组，创建对应tabBarButton
    for (UITabBarItem *item in _items) {
         ANTabBarButton *btn = [ANTabBarButton buttonWithType:UIButtonTypeCustom];
        // 给按钮赋值模型，按钮的内容由模型对应决定
        btn.item = item;
        btn.tag = self.buttons.count;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
        if (btn.tag == 0) { // 选中第0个
            [self btnClick:btn];
        }
        [self addSubview:btn];
        // 把按钮添加到按钮数组
        [self.buttons addObject:btn];
    }
}



@end
